import json
import random
import re

from django.shortcuts import render
from django.views import View
from django import http
from django_redis import get_redis_connection

from libs.captcha.captcha import captcha
from utils import constants
from utils.response_code import RET


class ImageCodeView(View):
    def get(self, request):
        # 1. 获取到当前的图片编号id

        code_id = request.GET.get('code_id')
        if not code_id:
            return http.HttpResponseBadRequest('code_id有误')

        # 2. 生成验证码
        name, text, image = captcha.generate_captcha()
        try:
            # 保存当前生成的图片验证码内容
            redis_conn = get_redis_connection('code')
            redis_conn.setex('img_%s' % code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        except Exception as e:
            return http.HttpResponseBadRequest('保存图片验证码失败')
        # 响应图片验证码
        return http.HttpResponse(image, content_type='image/jpeg')


class SMSCodeView(View):
    def post(self, request):
        # 1. 获取参数：手机号，图片验证码内容，图片验证码的编号 (随机值)
        # params_dict = json.loads(request.data)
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get("mobile")
        image_code = json_dict.get("image_code")
        image_code_id = json_dict.get("image_code_id")

        # 2. 校验参数(参数是否符合规则，判断是否有值)
        # 判断参数是否有值
        if not all([mobile, image_code, image_code_id]):
            # {"errno": "4100", "errmsg": "参数有误"}
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': '参数有误'})
        # 校验手机号是否正确
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': '手机号格式不正确'})

        # 3. 先从redis中取出真实的验证码内容
        try:
            redis_conn = get_redis_connection('code')
            real_image_code = redis_conn.get("img_" + image_code_id)
        except Exception as e:
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': '数据查询失败'})

        if not real_image_code:
            return http.JsonResponse({'errno': RET.NODATA, 'errmsg': '图片验证码过期'})

        # 4. 与用户的验证码内容进行对比，如果对比不一致，那么返回验证码输入错误
        real_image_code = real_image_code.decode()
        if real_image_code.upper() != image_code.upper():
            return http.JsonResponse({'errno': RET.DATAERR, 'errmsg': '验证码输入有误'})

        # 5. 如果一致，生成短信验证码的内容(随机数据)
        # 随机数字 ，保证数字长度为6位，不够在前面补上0
        sms_code_str = "%06d" % random.randint(0, 999999)
        print(sms_code_str)
        # 6. 发送短信验证码
        # result = CCP().send_template_sms(mobile, [sms_code_str, constants.SMS_CODE_REDIS_EXPIRES / 5], "1")
        # if result != 0:
        #     # 代表发送不成功
        #     return jsonify(errno=RET.THIRDERR, errmsg="发送短信失败")

        # 保存验证码内容到redis
        try:
            redis_conn.set("SMS_" + mobile, sms_code_str, constants.SMS_CODE_REDIS_EXPIRES)
        except Exception as e:
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': '数据保存失败'})

        # 7. 告知发送结果
        return http.JsonResponse({'errno': RET.OK, 'errmsg': '发送成功'})
